package cn.xw.controller;

import cn.xw.entity.AjaxResult;
import cn.xw.entity.Student;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;

/**
 * @author AnHui OuYang
 * @version 1.0
 */
@RestController
@RequestMapping("/login")
public class LoginController {

    private final StringRedisTemplate stringRedisTemplate;

    @Autowired
    public LoginController(StringRedisTemplate stringRedisTemplate) {
        this.stringRedisTemplate = stringRedisTemplate;
    }

    /***
     * 登录Controller
     * @param request 请求Request
     * @return String
     */
    @PostMapping
    public AjaxResult<Student> login(HttpServletRequest request) {
        // 获取用户名密码
        String name = request.getParameter("name");
        String password = request.getParameter("password");
        String code = request.getParameter("code");
        String codeKey = request.getParameter("codeKey");
        System.out.println("账号：" + name + "   密码：" + password + "   验证码：" + code);
        // 假设账号密码正确；；这里处理验证码
        //获取redis存的验证码
        String codeRedis = stringRedisTemplate.opsForValue().get(codeKey);
        //校验（不区分大小写）
        if (!code.equalsIgnoreCase(codeRedis)) {
            stringRedisTemplate.delete(codeKey);  //删除验证码
            return new AjaxResult<Student>(500, "验证码错误", null);
        }
        Student student = new Student(5564L, name, 22, "安徽六安", 93.5);
        return new AjaxResult<Student>(200, "登录成功", student);
    }

}
